﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.IO;
using Mc.Fe.Logic;
using Mc.Fe.Entities;
using System.Xml.XPath;
using System.Text;
using System.IO.Compression;
using System.Text.RegularExpressions;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.Checksums;
using System.Web.Hosting;

namespace Mc.Fe.WcfService
{
    public class XmlGenerator : System.Web.UI.Page
    {
        /// <summary>
        /// Descomprime el archivo CDR .Zip y lee datos de XML
        /// </summary>
        /// <param name="filePathExtact"></param>
        /// <param name="fileNameIn"></param>
        /// <returns></returns>
        public static DocumentResponse VerificarCDR(byte[] fileBytes)
        {
            try
            {
                #region Descarga el archivo CDR

                string pathCDR = System.Configuration.ConfigurationManager.AppSettings["PathCDR"];

                //*********************************************************************************
                //El archivo que recibe es un byte[] por lo tanto no se sabe cual es el nombre exacto del archivo.
                //Por ello, se guarda el archivo de manera temporal en el disco, luego guarda escribe el archivo 
                //CDR con el nombre original, el archivo XML, en el Método VerificarCDR()
                //*********************************************************************************                
                string fileNameZIP = pathCDR + "Temp.Zip"; //De forma temporal guarda el archivo
                File.WriteAllBytes(fileNameZIP, fileBytes);

                #endregion

                string fullFileNameExtact = string.Empty;

                #region Descomprimir el archivo CDR .Zip y obtiene el nombre completo del archivo XML
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(fileNameZIP)))
                {
                    ZipEntry theEntry = null;
                    while (theEntry == null)
                    {
                        theEntry = s.GetNextEntry();

                        Console.WriteLine(theEntry.Name);
                        fullFileNameExtact = pathCDR + theEntry.Name;

                        string directoryName = Path.GetDirectoryName(fullFileNameExtact);
                        string fileName = Path.GetFileName(theEntry.Name);

                        // create directory
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(fullFileNameExtact))
                            {

                                int size = 2048;
                                byte[] data = new byte[s.Length];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                            }
                        }
                    }
                }
                #endregion

                //Lee el archivo CDR XML
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(fullFileNameExtact);

                XmlNode applicationResponseNodes;
                applicationResponseNodes = xmlDocument.DocumentElement;
                XmlNamespaceManager xmlmanager = new XmlNamespaceManager(xmlDocument.NameTable);

                xmlmanager.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                xmlmanager.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                xmlmanager.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                xmlmanager.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");

                XmlNode referenceID = applicationResponseNodes.SelectSingleNode("//cac:DocumentResponse/cac:Response/cbc:ReferenceID", xmlmanager);
                XmlNode responseCode = applicationResponseNodes.SelectSingleNode("//cac:DocumentResponse/cac:Response/cbc:ResponseCode", xmlmanager);
                XmlNode description = applicationResponseNodes.SelectSingleNode("//cac:DocumentResponse/cac:Response/cbc:Description", xmlmanager);

                DocumentResponse result = new DocumentResponse();
                result.ReferenceID = referenceID.InnerText;
                result.ResponseCode = responseCode.InnerText;
                result.Description = description.InnerText;

                //Guarda el archivo Comprimido CDR en comprimido
                #region Guarda el archivo CDR en Comprimido .ZIP
                string zipFile = fullFileNameExtact.Substring(0, fullFileNameExtact.Length - 4) + ".Zip";
                ZipGenerator.ZipFile(zipFile, fullFileNameExtact);
                #endregion

                return result;
            }
            catch (Exception)
            {

                return null;
            }
        }

        /// <summary>
        /// Crea archivo XML/UBL de Nota Credito
        /// </summary> 
        /// <param name="factura"></param>
        /// <returns></returns>
        public static byte[] CreateNotaCreditoXML(Factura factura)
        {
            try
            {
                if (factura == null)
                    throw new Exception();

                string path = System.Configuration.ConfigurationManager.AppSettings["Path"];
                string correoContacto = System.Configuration.ConfigurationManager.AppSettings["CorreoContacto"];
                string fullFileName = HostingEnvironment.MapPath("~/XMLUBL/NOTACREDITO_PLANTILLA.xml");

                string tipoMoneda = string.Empty;
                string tipDoc = string.Empty;
                string nroDocumento = string.Empty;
                string montoLetras = factura.ImporteLetras;

                if (factura.Moneda.CompareTo("S") == 0)
                    tipoMoneda = Constantes.TipoMonedaSUNAT.SOLES;
                else
                    tipoMoneda = Constantes.TipoMonedaSUNAT.DOLARES;

                nroDocumento = factura.ReferenciaId;
                double factorIGV = Convert.ToDouble(factura.FactorIgv) / 100;

                string nroDocumentoReferencia = factura.NroDocumentoReferenciaSUNAT;
                tipDoc = factura.CodigoTipoDocumento;

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(fullFileName);

                XmlNode nodesFactura;
                nodesFactura = xmlDocument.DocumentElement;
                XmlNamespaceManager xmlmanager = new XmlNamespaceManager(xmlDocument.NameTable);

                xmlmanager.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                xmlmanager.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                xmlmanager.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                xmlmanager.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");

                #region Cabecera
                //1. Fecha de emisión
                XmlNode issueDate = nodesFactura.SelectSingleNode("cbc:IssueDate", xmlmanager); //1. Fecha de emisión
                issueDate.InnerText = string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(factura.Fecha)); //Fecha de Factura

                //2. Firma Digital

                //3. Apellidos y nombres, denominación o razón social
                XmlNode registrationName = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName", xmlmanager);
                registrationName.InnerText = System.Configuration.ConfigurationManager.AppSettings["NombreEmpresa"];

                //4. Nombre Comercial
                XmlNode nombreComercial = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name", xmlmanager);
                nombreComercial.InnerText = System.Configuration.ConfigurationManager.AppSettings["NombreEmpresa"];

                //5. Domicilio fiscal: Creo que es de la Empresa

                //Codigo Ubigeo
                XmlNode codigoUbigeo = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:ID", xmlmanager);
                codigoUbigeo.InnerText = System.Configuration.ConfigurationManager.AppSettings["CodigoUbigeoEmpresa"];

                XmlNode direccionCliente = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:StreetName", xmlmanager);
                direccionCliente.InnerText = System.Configuration.ConfigurationManager.AppSettings["DomicilioFiscalEmpresa"];

                //Opcional
                //XmlNode urbanizacion = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CitySubdivisionName", xmlmanager);
                //urbanizacion.InnerText = System.Configuration.ConfigurationManager.AppSettings["UrbanizacionEmpresa"]; //Urbanizacion

                XmlNode provincia = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CityName", xmlmanager);
                provincia.InnerText = System.Configuration.ConfigurationManager.AppSettings["ProvinciaEmpresa"];

                XmlNode departamento = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity", xmlmanager);
                departamento.InnerText = System.Configuration.ConfigurationManager.AppSettings["DepartamentoEmpresa"];

                XmlNode distrito = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:District", xmlmanager);
                distrito.InnerText = System.Configuration.ConfigurationManager.AppSettings["DistritoEmpresa"];

                XmlNode pais = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode", xmlmanager);
                pais.InnerText = System.Configuration.ConfigurationManager.AppSettings["PaisEmpresa"];

                //6. Número de RUC -- Parece que es de la empresa
                XmlNode numeroRuc = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cbc:CustomerAssignedAccountID", xmlmanager);
                numeroRuc.InnerText = System.Configuration.ConfigurationManager.AppSettings["RucEmpresa"];

                XmlNode tipoDocumentoRuc = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cbc:AdditionalAccountID", xmlmanager);
                tipoDocumentoRuc.InnerText = Constantes.Catalogo06.RUC;

                //7. Tipo de documento (Factura)

                //NC
                //XmlNode tipoDocFactura = nodesFactura.SelectSingleNode("//cbc:InvoiceTypeCode", xmlmanager);
                //tipoDocFactura.InnerText = tipDoc;

                //NOTAS
                XmlNodeList notasNodes = nodesFactura.SelectNodes("cbc:Note", xmlmanager);
                int notaPos = 0;
                foreach (XmlNode notaItemXml in notasNodes)
                {
                    notaItemXml.InnerText = string.Empty;
                    if (notaPos == 0 && !string.IsNullOrEmpty(factura.Motivo)) notaItemXml.InnerText = factura.Motivo;
                    notaPos++;
                }

                //NC
                //Referencia Documento
                nodesFactura.SelectSingleNode("cac:DiscrepancyResponse/cbc:ReferenceID", xmlmanager).InnerText = nroDocumentoReferencia;
                //Motivo
                //nodesFactura.SelectSingleNode("cac:DiscrepancyResponse/cbc:ResponseCode", xmlmanager).InnerText = "09";
                nodesFactura.SelectSingleNode("cac:DiscrepancyResponse/cbc:Description", xmlmanager).InnerText = factura.Motivo;

                nodesFactura.SelectSingleNode("cac:BillingReference/cac:InvoiceDocumentReference/cbc:ID", xmlmanager).InnerText = nroDocumentoReferencia;
                nodesFactura.SelectSingleNode("cac:BillingReference/cac:InvoiceDocumentReference/cbc:DocumentTypeCode", xmlmanager).InnerText = factura.TipoDocumentoReferencia;


                //8. Numeración, conformada por serie y número correlativo
                XmlNode nroFact = nodesFactura.SelectSingleNode("cbc:ID", xmlmanager);
                nroFact.InnerText = nroDocumento;

                //9. Tipo y número de documento de identidad del adquirente o usuario
                XmlNode numeroRucCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cbc:CustomerAssignedAccountID", xmlmanager);
                numeroRucCliente.InnerText = factura.RucCliente;

                XmlNode tipoDocRucCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cbc:AdditionalAccountID", xmlmanager);
                tipoDocRucCliente.InnerText = "6";

                //10. Apellidos y nombres, denominación o razón social del adquirente o usuario
                XmlNode nombreCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName", xmlmanager);
                nombreCliente.InnerText = factura.NombreCliente.Trim();

                //Direccion de cliente
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name", xmlmanager).InnerText = factura.NombreCliente.Trim(); //FALTA DATO

                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:ID", xmlmanager).InnerText = "150122"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName", xmlmanager).InnerText = factura.DireccionCliente.Trim(); //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName", xmlmanager).InnerText = string.Empty; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber", xmlmanager).InnerText = string.Empty; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:District", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode", xmlmanager).InnerText = "PE"; //FALTA DATO

                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail", xmlmanager).InnerText = correoContacto;
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Person/cbc:FirstName", xmlmanager).InnerText = string.Empty;//FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Person/cbc:MiddleName", xmlmanager).InnerText = string.Empty;//FALTA DATO

                //*********************************************************************************************************
                //Cabecera de la Factura
                //*********************************************************************************************************
                #region AdditionalInformation
                double valorVentaGravadas = (double)factura.ImporteSubTotal;
                double valorVentaInafectas = 0;
                double valorVentaExonerados = 0;
                double totalDescuentos = 0;


                XmlNode additionalMonetaryTotal = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal", xmlmanager);
                XmlNode additionalProperty = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty", xmlmanager);

                XmlNode additionalMonetaryTotalCopy = additionalMonetaryTotal.Clone();
                XmlNode additionalPropertyCopy = additionalProperty.Clone();

                XmlNode additionalInformation = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation", xmlmanager);
                additionalInformation.RemoveAll();

                //18. Total valor de venta - operaciones gravadas
                XmlNode additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                if (valorVentaGravadas > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.VALOR_VENTA_GRAVADA;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaGravadas);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //19. Total valor de venta - operaciones inafectas
                if (valorVentaInafectas > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.VALOR_VENTA_NO_GRAVADA;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaInafectas);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //20. Total valor de venta - operaciones exoneradas
                if (valorVentaExonerados > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.TOTAL_VALOR_VENTA_EXONERADO;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaExonerados);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //26. Total descuentos
                if (totalDescuentos > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.TOTAL_DESCUENTOS;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", totalDescuentos);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //31. Leyendas
                XmlNode additionalPropertyNew = additionalPropertyCopy.Clone();
                additionalPropertyNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo15.MONTO_LETRAS;
                additionalPropertyNew.SelectSingleNode("//cbc:Value", xmlmanager).InnerText = montoLetras; //FALTA DATO
                additionalInformation.AppendChild(additionalPropertyNew);
                additionalPropertyNew = null;
                #endregion

                //22. Sumatoria IGV
                XmlNode sumatoriaIGV = nodesFactura.SelectSingleNode("//cac:TaxTotal/cbc:TaxAmount", xmlmanager);
                sumatoriaIGV.Attributes["currencyID"].InnerText = tipoMoneda;
                sumatoriaIGV.InnerText = string.Format("{0:#####0.00}", factura.ImporteIGV);

                XmlNode sumatoriaIGV1 = nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount", xmlmanager);
                sumatoriaIGV1.Attributes["currencyID"].InnerText = tipoMoneda;
                sumatoriaIGV1.InnerText = string.Format("{0:#####0.00}", factura.ImporteIGV);

                XmlNode tipoMontoIGV = nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID", xmlmanager);
                tipoMontoIGV.InnerText = Constantes.Catalogo05.IGV;

                nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:Percent", xmlmanager).InnerText = string.Format("{0:#####0.00}", factura.FactorIgv);

                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                //23. Sumatoria ISC

                //cac:TaxTotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cbc:
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode


                //24. Sumatoria otros tributos
                //cac:TaxTotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                //25. Sumatoria otros Cargos
                //cac:LegalMonetaryTotal/cbc:ChargeTotalAmount



                //27. Importe total de la venta, cesión en uso o del servicio prestado
                nodesFactura.SelectSingleNode("//cac:LegalMonetaryTotal/cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                nodesFactura.SelectSingleNode("//cac:LegalMonetaryTotal/cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", factura.ImporteTotal); ;

                //28. Tipo de moneda en la cual se emite la factura electrónica
                nodesFactura.SelectSingleNode("cbc:DocumentCurrencyCode", xmlmanager).InnerText = tipoMoneda;

                //29. Tipo y número de la guía de remisión relacionada con la operación que se factura
                //Numero Guia
                //cac:DespatchDocumentReference/cbc:ID
                //Tipo Guia relacionada
                //cac:DespatchDocumentReference/cbc:DocumentTypeCode

                //30. Tipo y número de otro documento y código relacionado con la operación que se factura
                //Numero documento relacionado
                //cac:AdditionalDocumentReference/cbc:ID
                //cac:AdditionalDocumentReference/cbc:DocumentTypeCode




                //32. Importe de la percepción en moneda nacional
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:ReferenceAmount
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:PayableAmount
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:TotalAmount

                //36. Versión del UBL
                //cbc:UBLVersionID

                //37. Versión de la estructura del documento
                //cbc:CustomizationID

                //38. Valor referencial del servicio de transporte de bienes realizado por vía terrestre, determinado de conformidad con lo dispuesto en el DS N°010-2006-MTC, que aprobó la Tabla de Valores Referenciales para la aplicación del Sistema al servicio de transporte de bienes realizado por vía terrestre.
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:ReferenceAmount

                //39. Nombre y matrícula de la embarcación pesquera utilizada para efectuar la extracción y descarga de los bienes vendidos, en los casos que se hubiera utilizado dicho medio
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //40. Descripción del tipo y cantidad de la especie vendida
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //41. Lugar de la descarga
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //42. Fecha de la descarga
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //43. Numero de registro MTC
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //44. Configuracion vehicular
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //45. Punto de origen
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //46. Punto de destino
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //47. Valor referencial preliminar
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Name
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //48. Fecha de consumo
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //49. Total Valor de Venta - Operaciones gratuitas
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:PayableAmount


                #endregion

                #region Detalles
                XmlNodeList detalles = nodesFactura.SelectNodes("//cac:CreditNoteLine", xmlmanager);
                XmlNode itemCopy = detalles[0].Clone();

                XmlNodeList billingReference = itemCopy.SelectNodes("cac:BillingReference", xmlmanager);
                XmlNode billingReferenceCopy = billingReference[0].Clone();

                foreach (XmlNode item in billingReference)
                {
                    itemCopy.RemoveChild(item);
                }

                //Elimina nodos de detalle actual
                foreach (XmlNode itemRemove in detalles)
                {
                    nodesFactura.RemoveChild(itemRemove);
                }

                int pos = 1;
                //Añade nodos
                foreach (var detalleFactura in factura.Detalles)
                {
                    XmlNode newItemXml = itemCopy.Clone();

                    //33. Número de orden del Ítem
                    XmlNode correlativo = newItemXml.SelectSingleNode("//cbc:ID", xmlmanager);
                    correlativo.InnerText = pos.ToString(); //Item

                    //34. Código de producto
                    //cac:Item/cac:SellersItemIdentification/cbc:ID


                    //11. Unidad de medida por ítem
                    XmlNode cantidad = newItemXml.SelectSingleNode("//cbc:CreditedQuantity", xmlmanager);
                    cantidad.Attributes["unitCode"].InnerText = detalleFactura.UnidadMedida.Trim();
                    cantidad.InnerText = detalleFactura.Cantidad.ToString(); //12. Cantidad

                    //21. Valor de venta por ítem
                    XmlNode valorVentaItem = newItemXml.SelectSingleNode("//cbc:LineExtensionAmount", xmlmanager);
                    valorVentaItem.Attributes["currencyID"].InnerText = tipoMoneda;
                    valorVentaItem.InnerText = string.Format("{0:#####0.00}", detalleFactura.SubTotal);

                    //BillingReference
                    //***************************************************************************************************************
                    //Si usan isc
                    XmlNode billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_check";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "false";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Tipo de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "01";
                    newItemXml.AppendChild(billingReferenceNew);

                    //El monto de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //El monto de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_subtype";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "XXX";
                    newItemXml.AppendChild(billingReferenceNew);

                    //para el isc de tipo 3
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_price";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //descuento de línea
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //moneda o porcentaje del descuento. De no usarlo mantener las XXX
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "XXX";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Tipo de Afectación 
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "afec_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "10";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Valor referencial, solo para items gratuitos
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "ref_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Valor de Igv por línea
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "igv_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = Convert.ToDouble(factura.FactorIgv).ToString();
                    newItemXml.AppendChild(billingReferenceNew);

                    //total de linea sin igv y sin el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_import_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_desc_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "0";
                    newItemXml.AppendChild(billingReferenceNew);

                    //es el igv del total de línea sin el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_igv_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.00}", Convert.ToDouble(detalleFactura.SubTotal) * Convert.ToDouble(factura.FactorIgv));
                    newItemXml.AppendChild(billingReferenceNew);

                    //resultado del cálculo del ISC
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_import_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "0";
                    newItemXml.AppendChild(billingReferenceNew);

                    //valor unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_uvalue";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio)); ;
                    newItemXml.AppendChild(billingReferenceNew);

                    //precio unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_uprice";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio) * factorIGV);
                    newItemXml.AppendChild(billingReferenceNew);

                    //precio unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_xprice";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio) * factorIGV);
                    newItemXml.AppendChild(billingReferenceNew);

                    //***************************************************************************************************************

                    //13. Descripción detallada del servicio prestado, bien vendido o cedido en uso, indicando las características.
                    XmlNode descripcion = newItemXml.SelectSingleNode("//cac:Item/cbc:Description", xmlmanager);
                    descripcion.InnerText = detalleFactura.DescripcionProducto.Trim();

                    //14. Valor unitario por ítem
                    XmlNode valorUnitario = newItemXml.SelectSingleNode("//cac:Price/cbc:PriceAmount", xmlmanager);
                    valorUnitario.Attributes["currencyID"].InnerText = tipoMoneda; //15. Moneda
                    valorUnitario.InnerText = detalleFactura.Precio.ToString();

                    //15. Precio de venta unitario por item y código
                    XmlNode precioVenta = newItemXml.SelectSingleNode("//cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceAmount", xmlmanager);
                    precioVenta.Attributes["currencyID"].InnerText = tipoMoneda; //15. Moneda 
                    precioVenta.InnerText = detalleFactura.SubTotal.ToString(); //15. Precio Venta

                    XmlNode tipoPrecio = newItemXml.SelectSingleNode("//cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceTypeCode", xmlmanager);
                    tipoPrecio.InnerText = "01"; //15. Tipo de precio     

                    double precioConIGV = Convert.ToDouble(detalleFactura.Precio) * (1 + factorIGV);

                    //16. Afectación al IGV por ítem
                    XmlNode igvTaxAmount = newItemXml.SelectSingleNode("//cac:TaxTotal/cbc:TaxAmount", xmlmanager);
                    igvTaxAmount.Attributes["currencyID"].InnerText = tipoMoneda; //Moneda
                    igvTaxAmount.InnerText = string.Format("{0:#####0.000000}", precioConIGV); //Monto IGV

                    XmlNode igvTaxSubtotal = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount", xmlmanager); //IGV
                    igvTaxSubtotal.Attributes["currencyID"].InnerText = tipoMoneda; //Moneda
                    igvTaxSubtotal.InnerText = string.Format("{0:#####0.000000}", precioConIGV); //Monto IGV

                    XmlNode taxExemptionReasonCode = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cbc:TaxExemptionReasonCode", xmlmanager);
                    taxExemptionReasonCode.InnerText = "10"; //Afectación al IGV - Catálogo No. 07)

                    XmlNode taxSchemeID = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID", xmlmanager); //(Código de tributo - Catálogo No. 05
                    taxSchemeID.InnerText = System.Configuration.ConfigurationManager.AppSettings["CodigoTributo"];


                    //No es obligatorio - punto 16.
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                    //17. Sistema de ISC por ítem
                    //No es obligatorio - punto 17
                    //cac:TaxTotal/cbc:TaxAmount/@currencyID
                    //cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount/@currencyID
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cbc:TierRange
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID



                    //35. Valor referencial unitario por ítem en operaciones no onerosas y código
                    //cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceAmount/@currencyID
                    //cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceTypeCode

                    //50. Descuentos Globales
                    //cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount

                    //51. Descuentos por item
                    //cac:CreditNoteLine/cac:Allowancecharge/cbc:ChargeIndicator
                    //cac:CreditNoteLine/cac:Allowancecharge/cbc:Amount

                    nodesFactura.AppendChild(newItemXml);
                    pos++;
                }

                #endregion

                string newFileName = nroDocumento + ".xml";
                string newFullFileName = path + newFileName;

                xmlDocument.Save(newFullFileName);

                XmlDocument xmlDocumentSend = new XmlDocument();
                xmlDocumentSend.Load(newFullFileName);

                //var file = File.Open(newFullFileName, FileMode.Open);

                //Encoding encoding = Encoding.UTF8;                
                //byte[] docAsBytes = encoding.GetBytes(xmlDocumentSend.OuterXml);
                byte[] docAsBytesXML = File.ReadAllBytes(newFullFileName);

                return docAsBytesXML;

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// Crea archivo XML/UBL de Nota Debito
        /// </summary>
        /// <param name="factura"></param>
        /// <returns></returns>
        public static byte[] CreateNotaDebitoXML(Factura factura)
        {
            try
            {
                if (factura == null)
                    throw new Exception();

                string path = System.Configuration.ConfigurationManager.AppSettings["Path"];
                string correoContacto = System.Configuration.ConfigurationManager.AppSettings["CorreoContacto"];
                string fullFileName = HostingEnvironment.MapPath("~/XMLUBL/NOTADEBITO_PLANTILLA.xml");

                string tipoMoneda = string.Empty;
                string tipDoc = string.Empty;
                string nroDocumento = string.Empty;
                string montoLetras = factura.ImporteLetras;

                if (factura.Moneda.CompareTo("S") == 0)
                    tipoMoneda = Constantes.TipoMonedaSUNAT.SOLES;
                else
                    tipoMoneda = Constantes.TipoMonedaSUNAT.DOLARES;

                nroDocumento = factura.ReferenciaId;
                double factorIGV = Convert.ToDouble(factura.FactorIgv) / 100;

                string nroDocumentoReferencia = factura.NroDocumentoReferenciaSUNAT;
                tipDoc = factura.CodigoTipoDocumento;

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(fullFileName);

                XmlNode nodesFactura;
                nodesFactura = xmlDocument.DocumentElement;
                XmlNamespaceManager xmlmanager = new XmlNamespaceManager(xmlDocument.NameTable);

                xmlmanager.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                xmlmanager.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                xmlmanager.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                xmlmanager.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");

                #region Cabecera
                //1. Fecha de emisión
                XmlNode issueDate = nodesFactura.SelectSingleNode("cbc:IssueDate", xmlmanager); //1. Fecha de emisión
                issueDate.InnerText = string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(factura.Fecha)); //Fecha de Factura

                //2. Firma Digital

                //3. Apellidos y nombres, denominación o razón social
                XmlNode registrationName = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName", xmlmanager);
                registrationName.InnerText = System.Configuration.ConfigurationManager.AppSettings["NombreEmpresa"];

                //4. Nombre Comercial
                XmlNode nombreComercial = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name", xmlmanager);
                nombreComercial.InnerText = System.Configuration.ConfigurationManager.AppSettings["NombreEmpresa"];

                //5. Domicilio fiscal: Creo que es de la Empresa

                //Codigo Ubigeo
                XmlNode codigoUbigeo = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:ID", xmlmanager);
                codigoUbigeo.InnerText = System.Configuration.ConfigurationManager.AppSettings["CodigoUbigeoEmpresa"];

                XmlNode direccionCliente = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:StreetName", xmlmanager);
                direccionCliente.InnerText = System.Configuration.ConfigurationManager.AppSettings["DomicilioFiscalEmpresa"];

                //Opcional
                //XmlNode urbanizacion = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CitySubdivisionName", xmlmanager);
                //urbanizacion.InnerText = System.Configuration.ConfigurationManager.AppSettings["UrbanizacionEmpresa"]; //Urbanizacion

                XmlNode provincia = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CityName", xmlmanager);
                provincia.InnerText = System.Configuration.ConfigurationManager.AppSettings["ProvinciaEmpresa"];

                XmlNode departamento = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity", xmlmanager);
                departamento.InnerText = System.Configuration.ConfigurationManager.AppSettings["DepartamentoEmpresa"];

                XmlNode distrito = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:District", xmlmanager);
                distrito.InnerText = System.Configuration.ConfigurationManager.AppSettings["DistritoEmpresa"];

                XmlNode pais = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode", xmlmanager);
                pais.InnerText = System.Configuration.ConfigurationManager.AppSettings["PaisEmpresa"];

                //6. Número de RUC -- Parece que es de la empresa
                XmlNode numeroRuc = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cbc:CustomerAssignedAccountID", xmlmanager);
                numeroRuc.InnerText = System.Configuration.ConfigurationManager.AppSettings["RucEmpresa"];

                XmlNode tipoDocumentoRuc = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cbc:AdditionalAccountID", xmlmanager);
                tipoDocumentoRuc.InnerText = Constantes.Catalogo06.RUC;

                //7. Tipo de documento (Factura)
                //XmlNode tipoDocFactura = nodesFactura.SelectSingleNode("//cbc:InvoiceTypeCode", xmlmanager);
                //tipoDocFactura.InnerText = tipDoc;

                //NOTAS
                XmlNodeList notasNodes = nodesFactura.SelectNodes("cbc:Note", xmlmanager);
                int notaPos = 0;
                foreach (XmlNode notaItemXml in notasNodes)
                {
                    notaItemXml.InnerText = string.Empty;
                    if (notaPos == 0) notaItemXml.InnerText = factura.Motivo;
                    //nodesFactura.RemoveChild(notaItemXml);
                    notaPos++;
                }

                //NC
                //Referencia Documento
                nodesFactura.SelectSingleNode("cac:DiscrepancyResponse/cbc:ReferenceID", xmlmanager).InnerText = nroDocumentoReferencia;
                //Motivo
                //nodesFactura.SelectSingleNode("cac:DiscrepancyResponse/cbc:ResponseCode", xmlmanager).InnerText = "09";
                nodesFactura.SelectSingleNode("cac:DiscrepancyResponse/cbc:Description", xmlmanager).InnerText = factura.Motivo;

                nodesFactura.SelectSingleNode("cac:BillingReference/cac:InvoiceDocumentReference/cbc:ID", xmlmanager).InnerText = nroDocumentoReferencia;
                nodesFactura.SelectSingleNode("cac:BillingReference/cac:InvoiceDocumentReference/cbc:DocumentTypeCode", xmlmanager).InnerText = factura.TipoDocumentoReferencia;


                //8. Numeración, conformada por serie y número correlativo
                XmlNode nroFact = nodesFactura.SelectSingleNode("cbc:ID", xmlmanager);
                nroFact.InnerText = nroDocumento;

                //9. Tipo y número de documento de identidad del adquirente o usuario
                XmlNode numeroRucCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cbc:CustomerAssignedAccountID", xmlmanager);
                numeroRucCliente.InnerText = factura.RucCliente;

                XmlNode tipoDocRucCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cbc:AdditionalAccountID", xmlmanager);
                tipoDocRucCliente.InnerText = "6";

                //10. Apellidos y nombres, denominación o razón social del adquirente o usuario
                XmlNode nombreCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName", xmlmanager);
                nombreCliente.InnerText = factura.NombreCliente.Trim();

                //Direccion de cliente
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name", xmlmanager).InnerText = factura.NombreCliente.Trim(); //FALTA DATO

                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:ID", xmlmanager).InnerText = "150122"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName", xmlmanager).InnerText = factura.DireccionCliente.Trim(); //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName", xmlmanager).InnerText = string.Empty; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber", xmlmanager).InnerText = string.Empty; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:District", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode", xmlmanager).InnerText = "PE"; //FALTA DATO

                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail", xmlmanager).InnerText = correoContacto;
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Person/cbc:FirstName", xmlmanager).InnerText = string.Empty;//FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Person/cbc:MiddleName", xmlmanager).InnerText = string.Empty;//FALTA DATO

                //*********************************************************************************************************
                //Cabecera de la Factura
                //*********************************************************************************************************
                #region AdditionalInformation
                double valorVentaGravadas = (double)factura.ImporteSubTotal;
                double valorVentaInafectas = 0;
                double valorVentaExonerados = 0;
                double totalDescuentos = 0;


                XmlNode additionalMonetaryTotal = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal", xmlmanager);
                XmlNode additionalProperty = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty", xmlmanager);

                XmlNode additionalMonetaryTotalCopy = additionalMonetaryTotal.Clone();
                XmlNode additionalPropertyCopy = additionalProperty.Clone();

                XmlNode additionalInformation = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation", xmlmanager);
                additionalInformation.RemoveAll();

                //18. Total valor de venta - operaciones gravadas
                XmlNode additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                if (valorVentaGravadas > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.VALOR_VENTA_GRAVADA;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaGravadas);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //19. Total valor de venta - operaciones inafectas
                if (valorVentaInafectas > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.VALOR_VENTA_NO_GRAVADA;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaInafectas);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //20. Total valor de venta - operaciones exoneradas
                if (valorVentaExonerados > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.TOTAL_VALOR_VENTA_EXONERADO;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaExonerados);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //26. Total descuentos
                if (totalDescuentos > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.TOTAL_DESCUENTOS;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", totalDescuentos);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //31. Leyendas
                XmlNode additionalPropertyNew = additionalPropertyCopy.Clone();
                additionalPropertyNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo15.MONTO_LETRAS;
                additionalPropertyNew.SelectSingleNode("//cbc:Value", xmlmanager).InnerText = montoLetras; //FALTA DATO
                additionalInformation.AppendChild(additionalPropertyNew);
                additionalPropertyNew = null;
                #endregion

                //22. Sumatoria IGV
                XmlNode sumatoriaIGV = nodesFactura.SelectSingleNode("//cac:TaxTotal/cbc:TaxAmount", xmlmanager);
                sumatoriaIGV.Attributes["currencyID"].InnerText = tipoMoneda;
                sumatoriaIGV.InnerText = string.Format("{0:#####0.00}", factura.ImporteIGV);

                XmlNode sumatoriaIGV1 = nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount", xmlmanager);
                sumatoriaIGV1.Attributes["currencyID"].InnerText = tipoMoneda;
                sumatoriaIGV1.InnerText = string.Format("{0:#####0.00}", factura.ImporteIGV);

                XmlNode tipoMontoIGV = nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID", xmlmanager);
                tipoMontoIGV.InnerText = Constantes.Catalogo05.IGV;

                nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:Percent", xmlmanager).InnerText = string.Format("{0:#####0.00}", factura.FactorIgv);

                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                //23. Sumatoria ISC

                //cac:TaxTotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cbc:
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode


                //24. Sumatoria otros tributos
                //cac:TaxTotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                //25. Sumatoria otros Cargos
                //cac:LegalMonetaryTotal/cbc:ChargeTotalAmount



                //27. Importe total de la venta, cesión en uso o del servicio prestado
                //ND
                //No va
                //nodesFactura.SelectSingleNode("//cac:LegalMonetaryTotal/cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                //nodesFactura.SelectSingleNode("//cac:LegalMonetaryTotal/cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", factura.ImporteTotal); ;

                //28. Tipo de moneda en la cual se emite la factura electrónica
                nodesFactura.SelectSingleNode("cbc:DocumentCurrencyCode", xmlmanager).InnerText = tipoMoneda;

                //29. Tipo y número de la guía de remisión relacionada con la operación que se factura
                //Numero Guia
                //cac:DespatchDocumentReference/cbc:ID
                //Tipo Guia relacionada
                //cac:DespatchDocumentReference/cbc:DocumentTypeCode

                //30. Tipo y número de otro documento y código relacionado con la operación que se factura
                //Numero documento relacionado
                //cac:AdditionalDocumentReference/cbc:ID
                //cac:AdditionalDocumentReference/cbc:DocumentTypeCode




                //32. Importe de la percepción en moneda nacional
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:ReferenceAmount
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:PayableAmount
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:TotalAmount

                //36. Versión del UBL
                //cbc:UBLVersionID

                //37. Versión de la estructura del documento
                //cbc:CustomizationID

                //38. Valor referencial del servicio de transporte de bienes realizado por vía terrestre, determinado de conformidad con lo dispuesto en el DS N°010-2006-MTC, que aprobó la Tabla de Valores Referenciales para la aplicación del Sistema al servicio de transporte de bienes realizado por vía terrestre.
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:ReferenceAmount

                //39. Nombre y matrícula de la embarcación pesquera utilizada para efectuar la extracción y descarga de los bienes vendidos, en los casos que se hubiera utilizado dicho medio
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //40. Descripción del tipo y cantidad de la especie vendida
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //41. Lugar de la descarga
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //42. Fecha de la descarga
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //43. Numero de registro MTC
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //44. Configuracion vehicular
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //45. Punto de origen
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //46. Punto de destino
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //47. Valor referencial preliminar
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Name
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //48. Fecha de consumo
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //49. Total Valor de Venta - Operaciones gratuitas
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:PayableAmount


                #endregion

                #region Detalles
                XmlNodeList detalles = nodesFactura.SelectNodes("//cac:DebitNoteLine", xmlmanager);
                XmlNode itemCopy = detalles[0].Clone();

                XmlNodeList billingReference = itemCopy.SelectNodes("cac:BillingReference", xmlmanager);
                XmlNode billingReferenceCopy = billingReference[0].Clone();

                foreach (XmlNode item in billingReference)
                {
                    itemCopy.RemoveChild(item);
                }

                //Elimina nodos de detalle actual
                foreach (XmlNode itemRemove in detalles)
                {
                    nodesFactura.RemoveChild(itemRemove);
                }

                int pos = 1;
                //Añade nodos
                foreach (var detalleFactura in factura.Detalles)
                {
                    XmlNode newItemXml = itemCopy.Clone();

                    //33. Número de orden del Ítem
                    XmlNode correlativo = newItemXml.SelectSingleNode("//cbc:ID", xmlmanager);
                    correlativo.InnerText = pos.ToString(); //Item

                    //34. Código de producto
                    //cac:Item/cac:SellersItemIdentification/cbc:ID


                    //11. Unidad de medida por ítem
                    XmlNode cantidad = newItemXml.SelectSingleNode("//cbc:DebitedQuantity", xmlmanager);
                    cantidad.Attributes["unitCode"].InnerText = detalleFactura.UnidadMedida.Trim();
                    cantidad.InnerText = detalleFactura.Cantidad.ToString(); //12. Cantidad

                    //21. Valor de venta por ítem
                    XmlNode valorVentaItem = newItemXml.SelectSingleNode("//cbc:LineExtensionAmount", xmlmanager);
                    valorVentaItem.Attributes["currencyID"].InnerText = tipoMoneda;
                    valorVentaItem.InnerText = string.Format("{0:#####0.00}", detalleFactura.SubTotal);

                    //BillingReference
                    //***************************************************************************************************************
                    //Si usan isc
                    XmlNode billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_check";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "false";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Tipo de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "01";
                    newItemXml.AppendChild(billingReferenceNew);

                    //El monto de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //El monto de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_subtype";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "XXX";
                    newItemXml.AppendChild(billingReferenceNew);

                    //para el isc de tipo 3
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_price";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //descuento de línea
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //moneda o porcentaje del descuento. De no usarlo mantener las XXX
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "XXX";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Tipo de Afectación 
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "afec_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "10";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Valor referencial, solo para items gratuitos
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "ref_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Valor de Igv por línea
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "igv_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = Convert.ToDouble(factura.FactorIgv).ToString();
                    newItemXml.AppendChild(billingReferenceNew);

                    //total de linea sin igv y sin el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_import_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_desc_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "0";
                    newItemXml.AppendChild(billingReferenceNew);

                    //es el igv del total de línea sin el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_igv_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.00}", Convert.ToDouble(detalleFactura.SubTotal) * Convert.ToDouble(factura.FactorIgv));
                    newItemXml.AppendChild(billingReferenceNew);

                    //resultado del cálculo del ISC
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_import_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "0";
                    newItemXml.AppendChild(billingReferenceNew);

                    //valor unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_uvalue";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio)); ;
                    newItemXml.AppendChild(billingReferenceNew);

                    //precio unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_uprice";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio) * factorIGV);
                    newItemXml.AppendChild(billingReferenceNew);

                    //precio unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_xprice";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio) * factorIGV);
                    newItemXml.AppendChild(billingReferenceNew);

                    //***************************************************************************************************************

                    //13. Descripción detallada del servicio prestado, bien vendido o cedido en uso, indicando las características.
                    XmlNode descripcion = newItemXml.SelectSingleNode("//cac:Item/cbc:Description", xmlmanager);
                    descripcion.InnerText = detalleFactura.DescripcionProducto.Trim();

                    //14. Valor unitario por ítem
                    XmlNode valorUnitario = newItemXml.SelectSingleNode("//cac:Price/cbc:PriceAmount", xmlmanager);
                    valorUnitario.Attributes["currencyID"].InnerText = tipoMoneda; //15. Moneda
                    valorUnitario.InnerText = detalleFactura.Precio.ToString();

                    //15. Precio de venta unitario por item y código
                    XmlNode precioVenta = newItemXml.SelectSingleNode("//cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceAmount", xmlmanager);
                    precioVenta.Attributes["currencyID"].InnerText = tipoMoneda; //15. Moneda 
                    precioVenta.InnerText = detalleFactura.SubTotal.ToString(); //15. Precio Venta

                    XmlNode tipoPrecio = newItemXml.SelectSingleNode("//cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceTypeCode", xmlmanager);
                    tipoPrecio.InnerText = "01"; //15. Tipo de precio     

                    double precioConIGV = Convert.ToDouble(detalleFactura.Precio) * (1 + factorIGV);

                    //16. Afectación al IGV por ítem
                    XmlNode igvTaxAmount = newItemXml.SelectSingleNode("//cac:TaxTotal/cbc:TaxAmount", xmlmanager);
                    igvTaxAmount.Attributes["currencyID"].InnerText = tipoMoneda; //Moneda
                    igvTaxAmount.InnerText = string.Format("{0:#####0.000000}", precioConIGV); //Monto IGV

                    XmlNode igvTaxSubtotal = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount", xmlmanager); //IGV
                    igvTaxSubtotal.Attributes["currencyID"].InnerText = tipoMoneda; //Moneda
                    igvTaxSubtotal.InnerText = string.Format("{0:#####0.000000}", precioConIGV); //Monto IGV

                    XmlNode taxExemptionReasonCode = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cbc:TaxExemptionReasonCode", xmlmanager);
                    taxExemptionReasonCode.InnerText = "10"; //Afectación al IGV - Catálogo No. 07)

                    XmlNode taxSchemeID = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID", xmlmanager); //(Código de tributo - Catálogo No. 05
                    taxSchemeID.InnerText = System.Configuration.ConfigurationManager.AppSettings["CodigoTributo"];


                    //No es obligatorio - punto 16.
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                    //17. Sistema de ISC por ítem
                    //No es obligatorio - punto 17
                    //cac:TaxTotal/cbc:TaxAmount/@currencyID
                    //cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount/@currencyID
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cbc:TierRange
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID



                    //35. Valor referencial unitario por ítem en operaciones no onerosas y código
                    //cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceAmount/@currencyID
                    //cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceTypeCode

                    //50. Descuentos Globales
                    //cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount

                    //51. Descuentos por item
                    //cac:InvoiceLine/cac:Allowancecharge/cbc:ChargeIndicator
                    //cac:InvoiceLine/cac:Allowancecharge/cbc:Amount

                    nodesFactura.AppendChild(newItemXml);
                    pos++;
                }

                #endregion

                string newFileName = nroDocumento + ".xml";
                string newFullFileName = path + newFileName;

                xmlDocument.Save(newFullFileName);

                XmlDocument xmlDocumentSend = new XmlDocument();
                xmlDocumentSend.Load(newFullFileName);

                //var file = File.Open(newFullFileName, FileMode.Open);

                //Encoding encoding = Encoding.UTF8;                
                //byte[] docAsBytes = encoding.GetBytes(xmlDocumentSend.OuterXml);
                byte[] docAsBytesXML = File.ReadAllBytes(newFullFileName);

                return docAsBytesXML;

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// Crea un archivo XML/UBL de Factura / Boleta
        /// </summary>
        public static byte[] CreateFacturaXML(Factura factura)
        {
            try
            {
                if (factura == null)
                    throw new Exception();

                string path = System.Configuration.ConfigurationManager.AppSettings["Path"];
                string correoContacto = System.Configuration.ConfigurationManager.AppSettings["CorreoContacto"];
                string fullFileName = HostingEnvironment.MapPath("~/XMLUBL/FACTURA_PLANTILLA1.xml");

                string tipoMoneda = string.Empty;
                string tipDoc = string.Empty;
                string nroDocumento = string.Empty;
                string montoLetras = factura.ImporteLetras;

                if (factura.Moneda.Trim().CompareTo("S") == 0)
                    tipoMoneda = Constantes.TipoMonedaSUNAT.SOLES;
                else
                    tipoMoneda = Constantes.TipoMonedaSUNAT.DOLARES;

                nroDocumento = factura.ReferenciaId;
                double factorIGV = Convert.ToDouble(factura.FactorIgv) / 100;
                tipDoc = factura.CodigoTipoDocumento;

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(fullFileName);

                XmlNode nodesFactura;
                nodesFactura = xmlDocument.DocumentElement;
                XmlNamespaceManager xmlmanager = new XmlNamespaceManager(xmlDocument.NameTable);

                xmlmanager.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                xmlmanager.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                xmlmanager.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                xmlmanager.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");

                /*
                XmlNode nodo = xmlDocument.CreateNode("element", "ext:UBLExtensions", "");
                nodesFactura.AppendChild(nodo);
                
                string newFileName1 = nroDocumento + ".xml";
                string newFullFileName1 = path + newFileName1;

                xmlDocument.Save(newFullFileName1);

                return null;
                */

                #region Cabecera
                nodesFactura.SelectSingleNode("cbc:UUID", xmlmanager).InnerText = Guid.NewGuid().ToString();

                //1. Fecha de emisión
                XmlNode issueDate = nodesFactura.SelectSingleNode("cbc:IssueDate", xmlmanager); //1. Fecha de emisión
                issueDate.InnerText = string.Format("{0:yyyy-MM-dd}{1}", Convert.ToDateTime(factura.Fecha), "T00:00:00.000-00:00"); //Fecha de Factura

                //2. Firma Digital

                //3. Apellidos y nombres, denominación o razón social
                XmlNode registrationName = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName", xmlmanager);
                registrationName.InnerText = System.Configuration.ConfigurationManager.AppSettings["NombreEmpresa"];

                //4. Nombre Comercial
                XmlNode nombreComercial = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PartyName/cbc:Name", xmlmanager);
                nombreComercial.InnerText = System.Configuration.ConfigurationManager.AppSettings["NombreEmpresa"];

                //5. Domicilio fiscal: Creo que es de la Empresa

                //Codigo Ubigeo
                XmlNode codigoUbigeo = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:ID", xmlmanager);
                codigoUbigeo.InnerText = System.Configuration.ConfigurationManager.AppSettings["CodigoUbigeoEmpresa"];

                XmlNode direccionCliente = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:StreetName", xmlmanager);
                direccionCliente.InnerText = System.Configuration.ConfigurationManager.AppSettings["DomicilioFiscalEmpresa"];

                //Oficina
                nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName", xmlmanager).InnerText = System.Configuration.ConfigurationManager.AppSettings["DomicilioFiscalOficina"];
                nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber", xmlmanager).InnerText = System.Configuration.ConfigurationManager.AppSettings["DomicilioFiscalNumero"];

                //Opcional
                //XmlNode urbanizacion = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CitySubdivisionName", xmlmanager);
                //urbanizacion.InnerText = System.Configuration.ConfigurationManager.AppSettings["UrbanizacionEmpresa"]; //Urbanizacion

                XmlNode provincia = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CityName", xmlmanager);
                provincia.InnerText = System.Configuration.ConfigurationManager.AppSettings["ProvinciaEmpresa"];

                XmlNode departamento = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity", xmlmanager);
                departamento.InnerText = System.Configuration.ConfigurationManager.AppSettings["DepartamentoEmpresa"];

                XmlNode distrito = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cbc:District", xmlmanager);
                distrito.InnerText = System.Configuration.ConfigurationManager.AppSettings["DistritoEmpresa"];

                XmlNode pais = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode", xmlmanager);
                pais.InnerText = System.Configuration.ConfigurationManager.AppSettings["PaisEmpresa"];

                //6. Número de RUC -- Parece que es de la empresa
                XmlNode numeroRuc = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cbc:CustomerAssignedAccountID", xmlmanager);
                numeroRuc.InnerText = System.Configuration.ConfigurationManager.AppSettings["RucEmpresa"];

                XmlNode tipoDocumentoRuc = nodesFactura.SelectSingleNode("//cac:AccountingSupplierParty/cbc:AdditionalAccountID", xmlmanager);
                tipoDocumentoRuc.InnerText = Constantes.Catalogo06.RUC;

                //7. Tipo de documento (Factura)
                XmlNode tipoDocFactura = nodesFactura.SelectSingleNode("//cbc:InvoiceTypeCode", xmlmanager);
                tipoDocFactura.InnerText = tipDoc;

                //NOTAS
                XmlNodeList notasNodes = nodesFactura.SelectNodes("cbc:Note", xmlmanager);
                int notaPos = 0;
                foreach (XmlNode notaItemXml in notasNodes)
                {
                    notaItemXml.InnerText = string.Empty;
                    if (notaPos == 0 && !string.IsNullOrEmpty(factura.Glosa)) notaItemXml.InnerText = factura.Glosa;

                    if (notaPos == 1)
                    {
                        nodesFactura.RemoveChild(notaItemXml);
                        break;
                    }

                    notaPos++;
                }

                //8. Numeración, conformada por serie y número correlativo
                XmlNode nroFact = nodesFactura.SelectSingleNode("cbc:ID", xmlmanager);
                nroFact.InnerText = nroDocumento;

                //9. Tipo y número de documento de identidad del adquirente o usuario
                XmlNode numeroRucCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cbc:CustomerAssignedAccountID", xmlmanager);
                numeroRucCliente.InnerText = factura.RucCliente;

                XmlNode tipoDocRucCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cbc:AdditionalAccountID", xmlmanager);
                tipoDocRucCliente.InnerText = "6";

                //10. Apellidos y nombres, denominación o razón social del adquirente o usuario
                XmlNode nombreCliente = nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PartyLegalEntity/cbc:RegistrationName", xmlmanager);
                nombreCliente.InnerText = factura.NombreCliente.Trim();

                //Direccion de cliente
                //nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PartyName/cbc:Name", xmlmanager).InnerText = factura.NombreCliente.Trim();

                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:ID", xmlmanager).InnerText = "150122"; //Ubigeo del cliente
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:StreetName", xmlmanager).InnerText = factura.DireccionCliente.Trim(); //Direccion del cliente
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:AdditionalStreetName", xmlmanager).InnerText = string.Empty; //Oficina del cliente
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:BuildingNumber", xmlmanager).InnerText = string.Empty; //Numero domicilio del cliente
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CityName", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:CountrySubentity", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cbc:District", xmlmanager).InnerText = "LIMA"; //FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:PostalAddress/cac:Country/cbc:IdentificationCode", xmlmanager).InnerText = "PE"; //FALTA DATO

                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Contact/cbc:ElectronicMail", xmlmanager).InnerText = correoContacto;
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Person/cbc:FirstName", xmlmanager).InnerText = string.Empty;//FALTA DATO
                nodesFactura.SelectSingleNode("//cac:AccountingCustomerParty/cac:Party/cac:Person/cbc:MiddleName", xmlmanager).InnerText = string.Empty;//FALTA DATO

                //*********************************************************************************************************
                //Cabecera de la Factura
                //*********************************************************************************************************
                #region AdditionalInformation
                double valorVentaGravadas = (double)factura.ImporteSubTotal;
                double valorVentaInafectas = 0;
                double valorVentaExonerados = 0;
                double totalDescuentos = 0;


                XmlNode additionalMonetaryTotal = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal", xmlmanager);
                XmlNode additionalProperty = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty", xmlmanager);

                XmlNode additionalMonetaryTotalCopy = additionalMonetaryTotal.Clone();
                XmlNode additionalPropertyCopy = additionalProperty.Clone();

                XmlNode additionalInformation = nodesFactura.SelectSingleNode("//ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation", xmlmanager);
                additionalInformation.RemoveAll();

                //18. Total valor de venta - operaciones gravadas
                XmlNode additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                if (valorVentaGravadas > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.VALOR_VENTA_GRAVADA;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaGravadas);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //19. Total valor de venta - operaciones inafectas
                if (valorVentaInafectas > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.VALOR_VENTA_NO_GRAVADA;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaInafectas);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //20. Total valor de venta - operaciones exoneradas
                if (valorVentaExonerados > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.TOTAL_VALOR_VENTA_EXONERADO;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", valorVentaExonerados);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //26. Total descuentos
                if (totalDescuentos > 0)
                {
                    additionalMonetaryTotalNew = additionalMonetaryTotalCopy.Clone();
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo14.TOTAL_DESCUENTOS;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                    additionalMonetaryTotalNew.SelectSingleNode("//cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", totalDescuentos);
                    additionalInformation.AppendChild(additionalMonetaryTotalNew);
                    additionalMonetaryTotalNew = null;
                }

                //31. Leyendas
                XmlNode additionalPropertyNew = additionalPropertyCopy.Clone();
                additionalPropertyNew.SelectSingleNode("//cbc:ID", xmlmanager).InnerText = Constantes.Catalogo15.MONTO_LETRAS;
                additionalPropertyNew.SelectSingleNode("//cbc:Value", xmlmanager).InnerText = montoLetras; //FALTA DATO
                additionalInformation.AppendChild(additionalPropertyNew);
                additionalPropertyNew = null;
                #endregion

                //22. Sumatoria IGV
                XmlNode sumatoriaIGV = nodesFactura.SelectSingleNode("//cac:TaxTotal/cbc:TaxAmount", xmlmanager);
                sumatoriaIGV.Attributes["currencyID"].InnerText = tipoMoneda;
                sumatoriaIGV.InnerText = string.Format("{0:#####0.00}", factura.ImporteIGV);

                XmlNode sumatoriaIGV1 = nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount", xmlmanager);
                sumatoriaIGV1.Attributes["currencyID"].InnerText = tipoMoneda;
                sumatoriaIGV1.InnerText = string.Format("{0:#####0.00}", factura.ImporteIGV);

                XmlNode tipoMontoIGV = nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID", xmlmanager);
                tipoMontoIGV.InnerText = Constantes.Catalogo05.IGV;

                nodesFactura.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:Percent", xmlmanager).InnerText = string.Format("{0:#####0.00}", factura.FactorIgv);

                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                //23. Sumatoria ISC

                //cac:TaxTotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cbc:
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode


                //24. Sumatoria otros tributos
                //cac:TaxTotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                //25. Sumatoria otros Cargos
                //cac:LegalMonetaryTotal/cbc:ChargeTotalAmount



                //27. Importe total de la venta, cesión en uso o del servicio prestado
                nodesFactura.SelectSingleNode("//cac:LegalMonetaryTotal/cbc:PayableAmount", xmlmanager).Attributes["currencyID"].InnerText = tipoMoneda;
                nodesFactura.SelectSingleNode("//cac:LegalMonetaryTotal/cbc:PayableAmount", xmlmanager).InnerText = string.Format("{0:#####0.00}", factura.ImporteTotal); ;

                //28. Tipo de moneda en la cual se emite la factura electrónica
                nodesFactura.SelectSingleNode("cbc:DocumentCurrencyCode", xmlmanager).InnerText = tipoMoneda;


                //29. Tipo y número de la guía de remisión relacionada con la operación que se factura
                if (!string.IsNullOrEmpty(factura.NroGuias))
                {
                    //Numero Guia
                    //cac:DespatchDocumentReference/cbc:ID
                    nodesFactura.SelectSingleNode("cac:DespatchDocumentReference/cbc:ID", xmlmanager).InnerText = factura.NroGuias;
                    //Tipo Guia relacionada
                    nodesFactura.SelectSingleNode("cac:DespatchDocumentReference/cbc:DocumentTypeCode", xmlmanager).InnerText = Constantes.Catalogo01.GUIAREMISION;
                }
                else
                {
                    //Borra la entrada Guia de Remisión                        
                    XmlNode guia = nodesFactura.SelectSingleNode("cac:DespatchDocumentReference", xmlmanager);
                    if (guia != null)
                        nodesFactura.RemoveChild(guia);
                }

                //30. Tipo y número de otro documento y código relacionado con la operación que se factura
                //Numero documento relacionado
                //cac:AdditionalDocumentReference/cbc:ID
                //cac:AdditionalDocumentReference/cbc:DocumentTypeCode




                //32. Importe de la percepción en moneda nacional
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:ReferenceAmount
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:PayableAmount
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:TotalAmount

                //36. Versión del UBL
                //cbc:UBLVersionID

                //37. Versión de la estructura del documento
                //cbc:CustomizationID

                //38. Valor referencial del servicio de transporte de bienes realizado por vía terrestre, determinado de conformidad con lo dispuesto en el DS N°010-2006-MTC, que aprobó la Tabla de Valores Referenciales para la aplicación del Sistema al servicio de transporte de bienes realizado por vía terrestre.
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/sac:ReferenceAmount

                //39. Nombre y matrícula de la embarcación pesquera utilizada para efectuar la extracción y descarga de los bienes vendidos, en los casos que se hubiera utilizado dicho medio
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //40. Descripción del tipo y cantidad de la especie vendida
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //41. Lugar de la descarga
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //42. Fecha de la descarga
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //43. Numero de registro MTC
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //44. Configuracion vehicular
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //45. Punto de origen
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //46. Punto de destino
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //47. Valor referencial preliminar
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Name
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //48. Fecha de consumo
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalProperty/cbc:Value

                //49. Total Valor de Venta - Operaciones gratuitas
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:ID
                //ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent/sac:AdditionalInformation/sac:AdditionalMonetaryTotal/cbc:PayableAmount


                #endregion

                #region Detalles
                XmlNodeList detalles = nodesFactura.SelectNodes("//cac:InvoiceLine", xmlmanager);
                XmlNode itemCopy = detalles[0].Clone();

                XmlNodeList billingReference = itemCopy.SelectNodes("cac:BillingReference", xmlmanager);
                XmlNode billingReferenceCopy = billingReference[0].Clone();

                foreach (XmlNode item in billingReference)
                {
                    itemCopy.RemoveChild(item);
                }

                //Elimina nodos de detalle actual
                foreach (XmlNode itemRemove in detalles)
                {
                    nodesFactura.RemoveChild(itemRemove);
                }

                int pos = 1;
                //Añade nodos
                foreach (var detalleFactura in factura.Detalles)
                {
                    XmlNode newItemXml = itemCopy.Clone();

                    //33. Número de orden del Ítem
                    XmlNode correlativo = newItemXml.SelectSingleNode("//cbc:ID", xmlmanager);
                    correlativo.InnerText = pos.ToString(); //Item

                    //34. Código de producto
                    //cac:Item/cac:SellersItemIdentification/cbc:ID


                    //11. Unidad de medida por ítem
                    XmlNode cantidad = newItemXml.SelectSingleNode("//cbc:InvoicedQuantity", xmlmanager);
                    cantidad.Attributes["unitCode"].InnerText = detalleFactura.UnidadMedida.Trim();
                    cantidad.InnerText = detalleFactura.Cantidad.ToString(); //12. Cantidad

                    //21. Valor de venta por ítem
                    XmlNode valorVentaItem = newItemXml.SelectSingleNode("//cbc:LineExtensionAmount", xmlmanager);
                    valorVentaItem.Attributes["currencyID"].InnerText = tipoMoneda;
                    valorVentaItem.InnerText = string.Format("{0:#####0.00}", detalleFactura.SubTotal);

                    //BillingReference
                    //***************************************************************************************************************
                    //Si usan isc
                    XmlNode billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_check";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "false";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Tipo de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "01";
                    newItemXml.AppendChild(billingReferenceNew);

                    //El monto de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //El monto de Isc
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_subtype";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "XXX";
                    newItemXml.AppendChild(billingReferenceNew);

                    //para el isc de tipo 3
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_price";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //descuento de línea
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //moneda o porcentaje del descuento. De no usarlo mantener las XXX
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "XXX";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Tipo de Afectación 
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "afec_type";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "10";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Valor referencial, solo para items gratuitos
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "ref_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //Valor de Igv por línea
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "igv_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = Convert.ToDouble(factura.FactorIgv).ToString();
                    newItemXml.AppendChild(billingReferenceNew);

                    //total de linea sin igv y sin el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_import_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "";
                    newItemXml.AppendChild(billingReferenceNew);

                    //el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_desc_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "0";
                    newItemXml.AppendChild(billingReferenceNew);

                    //es el igv del total de línea sin el descuento
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "discount_igv_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.00}", Convert.ToDouble(detalleFactura.SubTotal) * Convert.ToDouble(factura.FactorIgv));
                    newItemXml.AppendChild(billingReferenceNew);

                    //resultado del cálculo del ISC
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "isc_import_value";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = "0";
                    newItemXml.AppendChild(billingReferenceNew);

                    //valor unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_uvalue";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio)); ;
                    newItemXml.AppendChild(billingReferenceNew);

                    //precio unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_uprice";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio) * factorIGV);
                    newItemXml.AppendChild(billingReferenceNew);

                    //precio unitario
                    billingReferenceNew = billingReferenceCopy.Clone();
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).Attributes["schemeID"].InnerText = "hidden_xprice";
                    billingReferenceNew.SelectSingleNode("cac:AdditionalDocumentReference/cbc:ID", xmlmanager).InnerText = string.Format("{0:#####0.000000}", Convert.ToDouble(detalleFactura.Precio) * factorIGV);
                    newItemXml.AppendChild(billingReferenceNew);

                    //***************************************************************************************************************

                    //13. Descripción detallada del servicio prestado, bien vendido o cedido en uso, indicando las características.
                    XmlNode descripcion = newItemXml.SelectSingleNode("//cac:Item/cbc:Description", xmlmanager);
                    descripcion.InnerText = detalleFactura.DescripcionProducto.Trim();

                    //14. Valor unitario por ítem
                    XmlNode valorUnitario = newItemXml.SelectSingleNode("//cac:Price/cbc:PriceAmount", xmlmanager);
                    valorUnitario.Attributes["currencyID"].InnerText = tipoMoneda; //15. Moneda
                    valorUnitario.InnerText = detalleFactura.Precio.ToString();

                    //15. Precio de venta unitario por item y código
                    XmlNode precioVenta = newItemXml.SelectSingleNode("//cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceAmount", xmlmanager);
                    precioVenta.Attributes["currencyID"].InnerText = tipoMoneda; //15. Moneda 
                    precioVenta.InnerText = detalleFactura.SubTotal.ToString(); //15. Precio Venta

                    XmlNode tipoPrecio = newItemXml.SelectSingleNode("//cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceTypeCode", xmlmanager);
                    tipoPrecio.InnerText = "01"; //15. Tipo de precio     

                    double precioConIGV = Convert.ToDouble(detalleFactura.Precio) * (1 + factorIGV);

                    //16. Afectación al IGV por ítem
                    XmlNode igvTaxAmount = newItemXml.SelectSingleNode("//cac:TaxTotal/cbc:TaxAmount", xmlmanager);
                    igvTaxAmount.Attributes["currencyID"].InnerText = tipoMoneda; //Moneda
                    igvTaxAmount.InnerText = string.Format("{0:#####0.000000}", precioConIGV); //Monto IGV

                    XmlNode igvTaxSubtotal = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount", xmlmanager); //IGV
                    igvTaxSubtotal.Attributes["currencyID"].InnerText = tipoMoneda; //Moneda
                    igvTaxSubtotal.InnerText = string.Format("{0:#####0.000000}", precioConIGV); //Monto IGV

                    XmlNode taxExemptionReasonCode = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cbc:TaxExemptionReasonCode", xmlmanager);
                    taxExemptionReasonCode.InnerText = "10"; //Afectación al IGV - Catálogo No. 07)

                    XmlNode taxSchemeID = newItemXml.SelectSingleNode("//cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID", xmlmanager); //(Código de tributo - Catálogo No. 05
                    taxSchemeID.InnerText = System.Configuration.ConfigurationManager.AppSettings["CodigoTributo"];


                    //No es obligatorio - punto 16.
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:Name
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:TaxTypeCode

                    //17. Sistema de ISC por ítem
                    //No es obligatorio - punto 17
                    //cac:TaxTotal/cbc:TaxAmount/@currencyID
                    //cac:TaxTotal/cac:TaxSubtotal/cbc:TaxAmount/@currencyID
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cbc:TierRange
                    //cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory/cac:TaxScheme/cbc:ID



                    //35. Valor referencial unitario por ítem en operaciones no onerosas y código
                    //cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceAmount/@currencyID
                    //cac:PricingReference/cac:AlternativeConditionPrice/cbc:PriceTypeCode

                    //50. Descuentos Globales
                    //cac:LegalMonetaryTotal/cbc:AllowanceTotalAmount

                    //51. Descuentos por item
                    //cac:InvoiceLine/cac:Allowancecharge/cbc:ChargeIndicator
                    //cac:InvoiceLine/cac:Allowancecharge/cbc:Amount

                    nodesFactura.AppendChild(newItemXml);
                    pos++;
                }

                #endregion

                string newFileName = nroDocumento + ".xml";
                string newFullFileName = path + newFileName;

                xmlDocument.Save(newFullFileName);

                XmlDocument xmlDocumentSend = new XmlDocument();
                xmlDocumentSend.Load(newFullFileName);

                newFullFileName = @"C:\Proyectos\Minera Colquisiri\Xml\Correctos\F003-00003124-PRUEBA.xml";

                //var file = File.Open(newFullFileName, FileMode.Open);

                //Encoding encoding = Encoding.UTF8;                
                //byte[] docAsBytes = encoding.GetBytes(xmlDocumentSend.OuterXml);
                byte[] docAsBytesXML = File.ReadAllBytes(newFullFileName);

                return docAsBytesXML;

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}